#!/usr/bin/env python3
"""
通知推送模块
支持飞书Webhook消息推送
"""

import requests
import logging
from datetime import datetime
from config import Config

logger = logging.getLogger(__name__)

class NotificationSender:
    """通知发送类 - 支持飞书Webhook"""
    
    def __init__(self, db_type='postgresql'):
        self.api_config = Config.get_api_config()
        self.webhook_url = self.api_config['lark_webhook']
        self.db_type = db_type
    
    def send_alert_report(self, title: str, content: str) -> bool:
        """发送告警报告到飞书群"""
        if not self.webhook_url:
            logger.error("未配置飞书Webhook URL")
            return False
        
        try:
            message = self._build_message(title, content)
            response = self._send_webhook(message)
            
            if response.status_code == 200:
                result = response.json()
                if result.get('code') == 0:
                    logger.info("飞书消息发送成功")
                    return True
                else:
                    logger.error(f"飞书消息发送失败: {result}")
                    return False
            else:
                logger.error(f"飞书Webhook请求失败: {response.status_code}")
                return False
                
        except Exception as e:
            logger.error(f"发送飞书消息异常: {e}")
            return False
    
    def _build_message(self, title: str, content: str) -> dict:
        """构建飞书消息体"""
        # 根据告警情况选择颜色
        template_color = "red" if "告警" in title else "green"
        
        return {
            "msg_type": "interactive",
            "card": {
                "config": {"wide_screen_mode": True},
                "header": {
                    "title": {"tag": "plain_text", "content": title},
                    "template": template_color
                },
                "elements": [
                    {"tag": "markdown", "content": content},
                    {
                        "tag": "div",
                        "fields": [
                            {
                                "is_short": True,
                                "text": {
                                    "tag": "lark_md",
                                    "content": f"**生成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
                                }
                            },
                            {
                                "is_short": True,
                                "text": {
                                    "tag": "lark_md", 
                                    "content": f"**数据来源**: Zabbix 6.0 ({self.db_type.upper()})"
                                }
                            }
                        ]
                    }
                ]
            }
        }
    
    def _send_webhook(self, message: dict) -> requests.Response:
        """发送Webhook请求"""
        return requests.post(
            self.webhook_url,
            headers={"Content-Type": "application/json"},
            json=message,
            timeout=30
        )
    
    def send_error_notification(self, error_message: str) -> bool:
        """发送错误通知"""
        title = "❌ Zabbix告警分析脚本执行失败"
        content = f"**错误信息**: {error_message}\n\n请检查脚本配置和运行环境。"
        
        return self.send_alert_report(title, content)
    
    def send_success_notification(self, alerts_count: int) -> bool:
        """发送执行成功通知"""
        if alerts_count > 0:
            title = f"🚨 Zabbix告警分析报告 ({alerts_count}个告警)"
        else:
            title = "✅ Zabbix系统状态正常"
        
        content = f"告警分析任务已完成，共处理 **{alerts_count}** 个告警。"
        return self.send_alert_report(title, content)